//门店受理JS

/**
 * datagrid行号
 * @type Number
 */
 var layerIndex=0;//layer订单详情弹出层返回的index
 var cancelIndex=0;//layer取消订单弹出层返回的index
 var isSingleCancel=false;//是否为单个订单取消,false为批量，true为单个
 var isSingleMakeFood=false;//是否为单个备单完成，false为批量，true为单个
 var isSingleStartMakeFood=false;//是否为单个开始备单，false为批量，true为单个
 var outCauseDescFlag=false;
 var insideCauseDescFlag=false;
 var rowPosion=0;
 $("#dop_datagrid_storefrontAccept").datagrid({
 	url : "",
	height : 350,
	pagination : true,
	fitColumns : false,
	singleSelect : false,
	fit : true,
	pageSize : 10,
	pageList : [10, 30, 50, 100],
	sortOrder : 'desc',
	rownumbers : true,
	showFooter : true,
	frozenColumns : [[]],
 		columns : [[{
		field : 'ck',
		checkbox : true
	}, {
		field : "id",
		width : 150,
		title : "主键",
		hidden : true
	}, {
		field : "code",
		width : 150,
		title : "订单号",
		align:'center',
		formatter:function(value,row,index){
			return "<a href='javascript:void(0);'  style='color:red;'>"+value+"</a>"
		}
	},{
		field : "statusText",
		width : 120,
		title : "状态",
		align:'center',
		formatter:function(value,row,index){
			if(row.readyStatus==1&&row.status==3){
				return value+"("+row.readyStatusStr+")";
			}else if(row.readyStatus==2&&row.status==4){
				return value+"("+row.readyStatusStr+")";
			}
			return value;
		}
	},{
		field : "deliveryManName",
		width : 80,
		title : "员工姓名",
		align:'center'
	}, 
	/*{
		field : "readyStatusStr",
		width : 80,
		title : "备单状态",
		align:'center'
	},
	*/ {
		field : "detail",
		width : 250,
		title : "订单明细",
		halign:"center",
		align:'left'
	}, {
		field : "custName",
		width : 80,
		title : "客户姓名",
		align:'center'
	}, {
		field : "telephone",
		width : 100,
		title : "电话",
		align:'left',
		halign:"center"
	}, {
		field : "custAddress",
		width : 280,
		title : "客户地址",
		align:'left',
		halign:"center"
	}, {
		field : "createDate",
		width : 120,
		title : "下单日期",
		align:'center',
		formatter:function(value,row,index){
			return new Date(value).format("yyyy-MM-dd hh:mm");
		}
	}, {
		field : "askSendTime",
		width : 120,
		title : "要求送达时间",
		align:'center',
		formatter:function(value,row,index){
			if(value==null){
				return "";
			}
			return new Date(value).format("yyyy-MM-dd hh:mm");
		}
	},
	// , {
	// field : "deliveryTime",
	// width : 150,
	// title : "配送时间"
	// }
	{
		field : "payMethodText",
		width : 80,
		title : "支付方式",
		align:'center'
	},  {
		field : "totalPrice",
		width : 80,
		title : "订单金额",
		halign:"center",
		align:'right'
	},{
		field : "orderTotalPrice",
		width : 80,
		title : "订单总金额",
		halign:"center",
		align:'right'
	},
	/*{
		field : "needWarmBoxText",
		width : 150,
		title : "需要保温箱",
		align:'center'
	},*/ {
		field : "storefrontName",
		width : 150,
		title : "店面",
		halign:"center",
		align:'left'
	}, {
		field : "foodDetail",
		width : 150,
		title : "菜品",
		hidden:true
	}]],
	/**
	 * 单元格单击事件
	 * @param {} rowIndex
	 * @param {} field
	 * @param {} value
	 */
	onClickCell:function(rowIndex, field, value){
		var row= $('#dop_datagrid_storefrontAccept').datagrid('getData').rows[rowIndex];
		rowPosion=rowIndex+1;
		/**
		 * 如果单击了订单号的行，弹出详细信息
		 */
		if(value==row.code){
			showOrderInfo(row);
		}
	}
	
 });
 
 $("#layerDialog").tabs({
 	onSelect:function(title,index){
		if(index==1){
			$("#codeDiv").html("订单编号:"+code.text());
			loadRecord();
		}
 	}
 });
/**
 * 加载订单状态记录
 */
 function loadRecord(){
 	var orderId=$("#orderId").val();
 	$.ajax({
 		url:"storefrontAcceptController.do?loadRecord",
 		type:"post",
 		data:{orderId:orderId},
 		dataType:"json",
 		cache:false,
 		success:function(data,textStatus){
 			var record=$("#orderRecord");
 			record.find("tr:eq(1)").nextAll().remove();
 			var recordStr="";
 			for(var i=0;i<data.length;i++){
 				recordStr+="<tr><td style='text-align: center;vertical-align: middle;'>"+data[i].changTimeStr+
 					"</td><td style='text-align: left;vertical-align: middle;'>"+data[i].recordDesc+"</td></tr>";
 			}
 			record.find("tr:eq(1)").hide();
 			record.append(recordStr);
 		},
 		error:function(textStatus, errorThrown){
			
 		}
 	});
 }
 
 /**
  * 显示订单详情
  * @param {} row
  */
 var orderId=$("#orderId");
 var code=$("#code");
 var source=$("#source");
 var createDate=$("#createDate");
 var custName=$("#custName");
 var telephone=$("#telephone");
 var askSendTime=$("#askSendTime");
 var custAddress=$("#custAddress");
 var orderTotalPrice=$("#orderTotalPrice");
 var deliveryPrice=$("#deliveryPrice");
 var totalPrice=$("#totalPrice");
 var preferentialPrice=$("#preferentialPrice");
 var note=$("#note");
 function showOrderInfo(row){
 	isSingleMakeFood=true;
 	orderId.val(row.id);
 	code.text(row.code);
 	source.text("");
 	createDate.text(new Date(row.createDate).format("yyyy-MM-dd hh:mm"));
 	custName.text(row.custName);
 	telephone.text(row.telephone);
 	askSendTime.text(new Date(row.askSendTime).format("yyyy-MM-dd hh:mm"));
 	custAddress.text(row.custAddress);
 	orderTotalPrice.text(row.orderTotalPrice+"元");
 	deliveryPrice.text(row.deliveryPrice+"元");
 	totalPrice.text(row.totalPrice+"元");
 	preferentialPrice.text("0元");
 	note.html(row.note);
	var foodDetail=$("#foodDetail");
	foodDetail.find("tr:first").nextAll().remove();
 	for(var i=0;i<row.foodDetail.length;i++){
 		var food=row.foodDetail[i];
 		foodDetail.append("<tr><td>"+food.food+"</td><td>"+food.count+"份</td><td>"+food.money+"元</td></tr>");
 	}
 	layerIndex=$.layer({
 		type:1,
 		shadeClose : true,
 		title : '<div><span style="line-height: 14px;">订单信息</span></div>',
		more:true,
		area : [ 1000, 500 ],
		page : {
			dom : '#layerDialog'
		},
		close:function(){
			/**
			 * 关闭后默认选择第一个
			 */
			 $("#layerDialog").tabs("select","订单详情");
			 var record=$("#orderRecord");
 			record.find("tr:eq(1)").show();
		}
 	});
 
 }
 
/**
 * 显示取消订单弹出层
 */
function showCancelDialog(){
	/**
	 * 如果为批量删除，执行批量取消的动作，否则为执行单个取消
	 */
	if(isSingleCancel==false){
		var seleted=$("#dop_datagrid_storefrontAccept").datagrid("getSelections");
 		if(seleted.length>0){
		 	cancelIndex=$.layer({
		 		type:1,
		 		shadeClose : true,
		 		title : '<div><span style="line-height: 14px;">取消订单</span></div>',
				more:true,
				area : [ 600, 400 ],
				page : {
					dom : '#cancelOrderDialog'
				}
		 	});
 		}else{
 			layerComm("请选择要取消的订单!","cancelOrder");
 		}
	}else{
		cancelIndex=$.layer({
		 		type:1,
		 		shadeClose : true,
		 		title : '<div><span style="line-height: 14px;">取消订单</span></div>',
				more:true,
				area : [ 600, 400 ],
				page : {
					dom : '#cancelOrderDialog'
				}
		 	});
	}
 }
 $("#cacel_cacel").click(function(){
 	layer.close(cancelIndex);
 });
 
  /**
  * 取消订单按钮订单击事件
  */
$("#cancelOrder").click(function(){
	  isSingleCancel=false;
	  showCancelDialog();
});
 /**
  * 单个订单取消按钮单击事件
  */
 $("#cancelSingleOrder").click(function(){
 	isSingleCancel=true;
 	showCancelDialog();
 });
 
 $("#cancel_ok").click(function(){
 	/**
 	 * 提交前进行验证
 	 */
 	checkInsideCauseDesc();
 	checkOutCauseDesc();
 	/**
 	 * 如果没有通过验证，不进行操作并给出提示
 	 */
 	if((insideCauseDescFlag&&outCauseDescFlag)==false){
 		return;
 	}
 	var outCauseDesc=$.trim($("#outCauseDesc").val());
 	var insideCauseDesc=$.trim($("#insideCauseDesc").val());
 	var arr=[];
 	/**
 	 * 批量取消
 	 */
 	if(isSingleCancel==false){
 		var seleted=$("#dop_datagrid_storefrontAccept").datagrid("getSelections");
 		for(var i=0;i<seleted.length;i++){
 			arr.push(seleted[i].id);
 		}
 	}else{
 		arr.push($("#orderId").val());
 	}
 	EapTools.doAction("storefrontAcceptController.do?cancelOrder", 
 		{outCauseDesc:outCauseDesc,insideCauseDesc:insideCauseDesc,arr:arr},
		true, function(data) {
			if(data.success){
				var obj=data.obj;
				if(isSingleCancel==true){
					if(obj.success==0){
						EapTip.alertOk("该订单不允许进行此操作！");
					}else{
						EapTip.alertOk("操作成功！");
					}
				}else{
					EapTip.alertOk("本次共提交"+obj.all+"笔订单，成功处理"+obj.success+"笔，有"+obj.fail+"笔订单不允许进行此操作！");
				}
				layer.close(cancelIndex);
				init();
				clearDesc();
			}
		});
 	
 });
 
 /**
  * 取消原因按钮单击事件，为文本域赋值
  */
 $(".cacelHref").click(function(){
 	$("#outCauseDesc").val($(this).text());
 });
 
 /**
  * 对订单取消外部原因进行判断
  */
 function checkOutCauseDesc(){
 	
 	var outCauseDesc=$.trim($("#outCauseDesc").val());
 	if(outCauseDesc.length==0){
 		layerComm("原因不得为空!","outCauseDesc");
 		outCauseDescFlag=false;
 		return;
 	}else if(outCauseDesc.length>200){
 		layerComm("原因不得超过200个字符!","outCauseDesc");
 		outCauseDescFlag=false;
 		return;
 	}
 	outCauseDescFlag=true;
 }
 
  /**
  * 对订单取消内部原因进行判断
  */
 function checkInsideCauseDesc(){
 	
 	var insideCauseDesc=$.trim($("#insideCauseDesc").val());
 	if(insideCauseDesc.length==0){
 		layerComm("原因不得为空!","insideCauseDesc");
 		insideCauseDesc=false;
 		return;
 	}else if(insideCauseDesc.length>200){
 		layerComm("原因不得超过200个字符!","insideCauseDesc");
 		insideCauseDescFlag=false;
 		return;
 	}
 	insideCauseDescFlag=true;
 }
 
 
 /**
  * 执行备单成功操作
  */
 function makeFoodSuccess(){
 	var arr=[];
	if(isSingleMakeFood==false){
	 	var seleted=$("#dop_datagrid_storefrontAccept").datagrid("getSelections");
	 	if(seleted.length>0){
	 		for(var i=0;i<seleted.length;i++){
				arr.push(seleted[i].id);
			}
	 	}
	 	else{
 			layerComm("请选择订单!","makeFoodSuccess");	
 		}
 	}else{
 		arr.push($("#orderId").val());
 	}
 	if(arr.length==0){
 		return;
 	}
 	layer.confirm('确定执行此操作吗？', function() {
 		EapTools.doAction("storefrontAcceptController.do?makeFoodSuccess", 
 			{arr:arr},
			true, function(data) {
			if(data.success){
				var obj=data.obj;
				if(isSingleMakeFood==true){
					if(obj.success==0){
						EapTip.alertOk("该订单不允许进行此操作！");
					}else{
						EapTip.alertOk("操作成功！");
					}
				}else{
					EapTip.alertOk("本次共提交"+obj.all+"笔订单，成功处理"+obj.success+"笔，有"+obj.fail+"笔订单不允许进行此操作！");
				}
			}
			
			init();
	  	});
 	});
 	
 }
 
 $("#makeFoodSuccess").click(function(){
 	isSingleMakeFood=false;
 	makeFoodSuccess();
 });
  $("#makeFoodSuccessSingle").click(function(){
 	isSingleMakeFood=true;
 	makeFoodSuccess();
 });
 
 $("#accept").click(function(){
	var arr=[];
 	var seleted=$("#dop_datagrid_storefrontAccept").datagrid("getSelections");
 	if(seleted.length>0){
 		for(var i=0;i<seleted.length;i++){
			arr.push(seleted[i].id);
		}
 	}
 	else{
		layerComm("请选择订单!","accept");	
		return;
	}
	layer.confirm('确定要接受订单吗？', function() {
 		EapTools.doAction("storefrontAcceptController.do?accept", 
 			{ids:arr},
			true, function(data) {
			if(data.success){
				EapTip.msgOk("操作成功!");
				init();
			}
	  	});
 	});
 	
 });
 
 /**
  * 执行开始备单操作
  */
 function startMakeFood(){
 	var arr=[];
	if(isSingleStartMakeFood==false){
	 	var seleted=$("#dop_datagrid_storefrontAccept").datagrid("getSelections");
	 	if(seleted.length>0){
	 		for(var i=0;i<seleted.length;i++){
				arr.push(seleted[i].id);
			}
	 	}
	 	else{
 			layerComm("请选择订单!","startMakeFood");	
 		}
 	}else{
 		arr.push($("#orderId").val());
 	}
 	if(arr.length==0){
 		return;
 	}
 	layer.confirm('确定执行此操作吗？', function() {
 		EapTools.doAction("storefrontAcceptController.do?startMakeFood", 
 			{arr:arr},
			true, function(data) {
			var obj=data.obj;
			if(data.success){
				EapTip.alertOk("本次共提交"+obj.all+"笔订单，成功处理"+obj.success+"笔，有"+obj.fail+"笔订单不允许进行此操作！");
				init();
			}
	  	});
 	});
 }
 
 $("#startMakeFood").click(function(){
 	isSingleStartMakeFood=false;
 	startMakeFood();
 });
 $("#startSingleMakeFood").click(function(){
 	isSingleStartMakeFood=true;
 	startMakeFood();
 });
 /**
  * 清空原因
  */
 function clearDesc(){
 	$("#insideCauseDesc,#outCauseDesc").val("");
 }
 
 
 /**
  * 上一条单击事件
  */
  $("#proOrder").click(function(){
  	var rowsCount= $('#dop_datagrid_storefrontAccept').datagrid("getRows").length;
  	rowPosion-=1;
  	if(rowPosion<=0){
  		rowPosion=0;
  	}
 	var row= $('#dop_datagrid_storefrontAccept').datagrid('getData').rows[rowPosion];
 	
 	showOrderInfo(row);
 });
 
 /**
  * 下一条单击事件
  */
 $("#nextOrder").click(function(){
 	var rowsCount= $('#dop_datagrid_storefrontAccept').datagrid("getRows").length;
 	rowPosion+=1;
 	if(rowPosion>=rowsCount){
 		rowPosion=rowsCount-1;
 	}
	var row= $('#dop_datagrid_storefrontAccept').datagrid('getData').rows[rowPosion];
 	showOrderInfo(row);
 });
 


/**
 * 异步加载配送人员
 */
function loadDeliverMan(){
	var list=$("#deliveryManList");
	list.children().remove();
	EapTools.doAction("deliveryManController.do?getOpenAndReceiveDeliveryMan", null,
		true, function(data) {
			for(var i=0;i<data.length;i++){
				list.append("<option value="+data[i].id+">"+data[i].name+"</option>");
			}
	});
}
 /**
  * 显示送人员
  */
$("#divide").click(function(){
	var seleted=$("#dop_datagrid_storefrontAccept").datagrid("getSelections");
	if(seleted.length>0){
		loadDeliverMan();
		layerIndex=$.layer({
			type:1,
	 		shadeClose : true,
	 		title : '<div><span style="line-height: 14px;">选择配送人员</span></div>',
			more:true,
			area : [ "450", "100" ],
			page : {
				dom : '#deliveryManDiv'
			}
		});
	}else{
		layerComm("请选择订单!","divide");
	}
});

/**
 * 确认分配人员
 */
$("#divide_ok").click(function(){
	var seleted=$("#dop_datagrid_storefrontAccept").datagrid("getSelections");
	var arr=[];
	for(var i=0;i<seleted.length;i++){
		arr.push(seleted[i].id);
	}
	
	EapTools.doAction("storefrontAcceptController.do?delive", {ids:arr,manId:$("#deliveryManList").val()},
		true, function(data) {
			layer.close(layerIndex);
			layer.alert("操作成功！本次共分配"+data.success+"笔订单，有"+data.faild+"笔订单不允许进行分配！", 1);
			init();
	});
	
});
/***
 * layer提示信息封装
 * @param msg  消息内容
 * @param id   要显示位置的元素ID
 */
function layerComm(msg,id){
	layer.tips(msg, document.getElementById(id), {
		guide : 2,
		time : 3,
		more:true
	});
}
 
/**
 * 绑定订单状态列表
 */
EapTools.doAction("storefrontAcceptController.do?getOrderStatus", {}, false, function(
		data) {
	var selectorArray = [];
	//selectorArray.push("<option value=''>---请选择---</option>");
	$.each(data.attributes, function(key, value) {
		selectorArray.push("<option value='", key, "'>", value,
				"</option>");
	}); 

	$("select[code='queryStatus']").append(selectorArray.join(""));
	$("select[code='queryStatus']").val("1");
	//$("select[id='status']").append(selectorArray.join(""));
});

/**
 * 绑定支付方式列表
 */
EapTools.doAction("orderEnumController.do?getPayMethod", {}, true, function(
		data) {
	var selectorArray = [];
	selectorArray.push("<option value=''>---请选择---</option>");
	$.each(data.attributes, function(key, value) {
		selectorArray.push("<option value='", key, "'>", value,
				"</option>");
	}); 

	$("select[code='payMethod']").append(selectorArray.join(""));
	//$("select[id='payMethod']").append(selectorArray.join(""));
});
 /**
  * 获取查询条件参数
  */
function getQueryParam(){
	return {
		code : $("input[code='queryCode']").val(),
		deliveryManName : $("input[code='queryDeliveryManName']").val(),
		status : $("select[code='queryStatus']").val() || 0,
		custName : $("input[code='queryCustName']").val(),
		createDate : $("input[code='queryCreateDate']").val(),
		askSendTime:$("input[code='queryAskSendTime']").val(),
		payMethod : $("select[code='payMethod']").val() || 0
	};
}


var p = $("#dop_datagrid_storefrontAccept").datagrid('getPager');
$(p).pagination(
		{
			onSelectPage : function(pageNumber, pageSize) {
				var params = $.extend({
					pageNum : pageNumber,
					pageSize : pageSize
				}, getQueryParam());
				EapTools.doAction("storefrontAcceptController.do?query", params,
						true, function(data) {
							$("#dop_datagrid_storefrontAccept").datagrid('loadData',
									{
										"rows" : data.list,
										"total" : data.count
									} || {});
						});
			}
		});
		
		
/**
 * 格式化日期
 * @param {} fmt
 * @return {}
 */
Date.prototype.Format = function(fmt) 
{ //author: meizz 
  var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S"  : this.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); 
  return fmt; 
}
		

/**
 * 查询按钮事件
 */
$("#search").click(function(){
	init();
});
		
/**
 * 执行init
 */
init();
function init()
{
	var options = $("#dop_datagrid_storefrontAccept").datagrid('getPager').data("pagination").options;
	var pageSize = options.pageSize;
	var params = $.extend({
		pageNum : 1,
		pageSize : pageSize
	}, getQueryParam());
	EapTools.doAction("storefrontAcceptController.do?query", params, true, function(data)
	{
		
		$("#dop_datagrid_storefrontAccept").datagrid('loadData', {
			"rows" : data.list,
			"total" : data.count
		} || {});
		var p = $("#dop_datagrid_storefrontAccept").datagrid('getPager');
		$("td:last", p).find("a").click();
	});
	
}

